﻿using Coldairarrow.Business.PB;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.IT;
using Coldairarrow.Entity.PB;
using Coldairarrow.Entity.TD;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Coldairarrow.Business.TD
{
    public partial class TD_ScrapBusiness : BaseBusiness<TD_Scrap>, ITD_ScrapBusiness, ITransientDependency
    {
        readonly IOperator _operator;
        readonly ICheckOperation _check;
        public TD_ScrapBusiness(IDbAccessor db, IOperator @operator, ICheckOperation @check)
            : base(db)
        {
            _operator = @operator;
            _check = @check;
        }

        #region 外部接口

        public async Task<PageResult<TD_Scrap>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<TD_Scrap>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<TD_Scrap, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<TD_Scrap> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(TD_Scrap data)
        {
            await InsertAsync(data);
        }

        public async Task UpdateDataAsync(TD_Scrap data)
        {
            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }

        /// <summary>
        /// 保存待维报废订单
        /// </summary>
        /// <param name="data">保存数据</param>
        /// <returns></returns>
         [Transactional]
        public async Task AddScrapInfo(TD_ScrapInfo data)
        {
            //报废单编号
            string ScrapId = IdHelper.GetId();
            double Nums = 0;
            //创建报废单明细
            string Updatesql = "";
            List<TD_ScrapDetail> tD_ScrapDetails = new List<TD_ScrapDetail>();
            for (int i=0;i<data.Detailinfo.Count;i++) {
                TD_ScrapDetail tD_ScrapDetail = new TD_ScrapDetail();
                tD_ScrapDetail.Id = IdHelper.GetId();
                tD_ScrapDetail.ParentId = ScrapId;
                tD_ScrapDetail.MaterialId = data.Detailinfo[i].MaterialId;
                 Nums+=  tD_ScrapDetail.ScrapNums = data.Detailinfo[i].ScrapNums;
                tD_ScrapDetail.LocationId = data.Detailinfo[i].LocalId;
                tD_ScrapDetail.CreateTime = DateTime.Now;
                tD_ScrapDetail.CreatorId = _operator.UserId;
                tD_ScrapDetail.Deleted = false;
                tD_ScrapDetail.OutNum = 0;
                if (!tD_ScrapDetail.LocationId.IsNullOrEmpty()) {
                    Updatesql += "UPDATE IT_LocalMaterial SET Nums_R = IFNULL(Nums_R,0) +'" + tD_ScrapDetail.ScrapNums + "' WHERE LocalId='" + tD_ScrapDetail.LocationId + "' AND MaterialId='" + tD_ScrapDetail.MaterialId + "';";
                }
                tD_ScrapDetails.Add(tD_ScrapDetail);
            }
            //创建报废单主表
            TD_Scrap tD_Scrap = new TD_Scrap();
            tD_Scrap.Id = ScrapId;
            tD_Scrap.Nums = Nums;
            tD_Scrap.QrCode = "98," + ScrapId;
            tD_Scrap.State = 0;
            tD_Scrap.CreatorId = _operator.UserId;
            tD_Scrap.CreateTime = DateTime.Now;
            tD_Scrap.Remarks = data.Remarks;
            tD_Scrap.Deleted = false;
            await Db.InsertAsync<TD_ScrapDetail>(tD_ScrapDetails);
            await Db.InsertAsync<TD_Scrap>(tD_Scrap);
            await Db.ExecuteSqlAsync(Updatesql);
         
        }

        public async Task<TD_ScrapMainList> GetScrapMainList(string Id)
        {
            var Maindata = await Db.GetIQueryable<TD_Scrap>().Where(m=>m.Id== Id).FirstOrDefaultAsync(); 
            TD_ScrapMainList tD_ScrapMainList = new TD_ScrapMainList();
            //获取报废单主表
            tD_ScrapMainList.Id = Maindata.Id;
                tD_ScrapMainList.Nums = Maindata.Nums;
            tD_ScrapMainList.CreatorId = Maindata.CreatorId;
            tD_ScrapMainList.State = Maindata.State;
            tD_ScrapMainList.CreateTime = Maindata.CreateTime;
            tD_ScrapMainList.Deleted = Maindata.Deleted;
            tD_ScrapMainList.Remarks = Maindata.Remarks;
            tD_ScrapMainList.QrCode = Maindata.QrCode;
            String sql = "select t.*,kucun.Num from (SELECT a.Id,a.ScrapNums, a.MaterialId materialId, m.`Name` MaterialIdName, m.`Code` materialCode,  m.Spec MaterSpec, location.`Name`  LocalIdName, location.`Id`  LocalId,rack.`Name` AS RackName, area.`Name` StoareaName,IFNULL(a.OutNum,0) OutNum FROM TD_ScrapDetail AS a LEFT JOIN PB_Material AS m ON a.MaterialId = m.Id LEFT JOIN PB_Location AS location ON a.LocationId = location.Id  LEFT JOIN PB_Rack AS rack on location.RackId = rack.Id LEFT JOIN PB_StorArea AS area on location.AreaId = area.Id  WHERE a.ParentId='" + Id+ "' ) as t LEFT JOIN(select IFNULL(sum(Num),0) Num,LocalId,MaterialId from IT_LocalDetail GROUP BY LocalId, MaterialId) AS kucun on t.LocalId = kucun.LocalId and t.materialId = kucun.MaterialId";
            var list =await Db.GetListBySqlAsync<TD_ScrapDetailDto>(sql);
            tD_ScrapMainList.Detail = list;
            return tD_ScrapMainList;
        }

        public async Task UpdateScrapInfo(TD_ScrapInfo Data)
        {
            List<TD_ScrapDetail> PickUpList = await Db.GetIQueryable<TD_ScrapDetail>().Where(x => x.ParentId == Data.Id).ToListAsync();
            string sqlMain = string.Empty;
            string StepNumber = string.Empty;
            string Updatesql = "";
            foreach (var item in PickUpList)
            {
                sqlMain += @" update  IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)-" + item.ScrapNums + " WHERE LocalId='" + item.LocationId + "' AND MaterialId='" + item.MaterialId + "'; ";
            }
            //清空库存占用
            await ExecuteSqlAsync(sqlMain);
            await ExecuteSqlAsync(" delete from TD_ScrapDetail where ParentId='" + Data.Id + "'");


            List<TD_ScrapDetail> tD_ScrapDetails = new List<TD_ScrapDetail>();
            double Nums = 0;
            for (int i = 0; i < Data.Detailinfo.Count; i++)
            {
                TD_ScrapDetail tD_ScrapDetail = new TD_ScrapDetail();
                tD_ScrapDetail.Id = IdHelper.GetId();
                tD_ScrapDetail.ParentId = Data.Id;
                tD_ScrapDetail.MaterialId = Data.Detailinfo[i].MaterialId;
                Nums += tD_ScrapDetail.ScrapNums = Data.Detailinfo[i].ScrapNums;
                tD_ScrapDetail.LocationId = Data.Detailinfo[i].LocalId;
                tD_ScrapDetail.CreateTime = DateTime.Now;
                tD_ScrapDetail.CreatorId = _operator.UserId;
                tD_ScrapDetail.Deleted = false;
                tD_ScrapDetail.OutNum = 0;
                if (!tD_ScrapDetail.LocationId.IsNullOrEmpty())
                {
                    Updatesql += "UPDATE IT_LocalMaterial SET Nums_R = IFNULL(Nums_R,0) +'" + tD_ScrapDetail.ScrapNums + "' WHERE LocalId='" + tD_ScrapDetail.LocationId + "' AND MaterialId='" + tD_ScrapDetail.MaterialId + "';";
                }
                tD_ScrapDetails.Add(tD_ScrapDetail);
            }
            await Db.InsertAsync<TD_ScrapDetail>(tD_ScrapDetails);
            string sqlmain = "UPDATE  TD_Scrap set Nums=" + Nums + " WHERE ID='" + Data.Id + "'";
            await Db.ExecuteSqlAsync(sqlmain);
            await Db.ExecuteSqlAsync(Updatesql);
        }


        /// <summary>
        /// PDA报废扫码出库
        /// </summary>
        /// <param name="data">数据源</param>
        /// <returns></returns>
        public async Task GetAdd(TD_ScrapData data)
        {
            Base_User basedata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            var Base_User =await Db.GetIQueryable<Base_User>().Where(m=>m.Id==_operator.UserId).FirstOrDefaultAsync();
            var PackModel = data.MaterialQrCode.Split(',')[0].ToString();
            string sqlMain = "";
            //获取二维码请求头
            var QrcodeModel = data.QrCode.Split(',')[0].ToString();
            var materialId = string.Empty;
            List<PB_UnLoadList> UnLoadList = new List<PB_UnLoadList>();
            List<PB_StockLog> StockLogList = new List<PB_StockLog>();
            List<PB_Unpacking> UnpackingList = new List<PB_Unpacking>();
            List<PB_UnpackingDetail> UnpackingDetailList = new List<PB_UnpackingDetail>();
            if (QrcodeModel=="98") {
                var ScrapId = data.QrCode.Split(',')[1].ToString();
                var locationId = data.LocationQrCode.Split(',')[1].ToString();
                //报废单扫码单个物料
                if (PackModel == "04") {
                   
                    var model = data.MaterialQrCode.Split(',');
                    if (model.Length > 2)
                    {
                        if (model.Length < 4)
                        {
                            throw new BusException("请扫描正确的二维码信息");
                        }
                        else
                        {
                            materialId = model?[3].ToString();
                        }
                    }
                    else
                    {
                        materialId = model?[1].ToString();
                    }
                    var tD_Scrap = await Db.GetIQueryable<TD_Scrap>().Where(m => m.Id == ScrapId).FirstOrDefaultAsync();
                    if (tD_Scrap.State == 1)
                    {
                        var td_scrap = await Db.GetIQueryable<TD_ScrapDetail>().Where(m => m.ParentId == tD_Scrap.Id && m.LocationId == locationId && m.MaterialId == materialId).FirstOrDefaultAsync();
                        if (td_scrap == null)
                        {
                            throw new BusException("请检查报废单是否存在该物料信息!");
                        }        
                        List<IT_LocalDetail> IT_LocalDetaillist = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.MaterialId == materialId && x.PackId == "" && x.LocalId == locationId).ToListAsync();
                        if (IT_LocalDetaillist.Count > 0)
                        {
                            //汇总当前货位的物料总数量
                            var matersumnums = IT_LocalDetaillist.GroupBy(x => new { x.MaterialId, x.StorId, x.LocalId }).Select(x => new { MaterialId = x.Key.MaterialId, LocalId = x.Key.LocalId, StorId = x.Key.StorId, materNums = x.Sum(i => i.Num) }).FirstOrDefault();
                            if (data.Nums > matersumnums.materNums)
                            {
                                throw new BusException("请检查当前货位物料的数量是否满足出库的数量");
                            }

                            //获取备货单明细信息
                            var detaildata = await Db.GetIQueryable<TD_ScrapDetail>().Where(x => x.ParentId == tD_Scrap.Id && x.MaterialId == materialId && x.LocationId == locationId).FirstOrDefaultAsync();
                            if (detaildata == null)
                            {
                                throw new BusException("请检查扫描的物料是否存在备货单中");
                            }
                            double? dnum = 0;
                            //明细中要出库的数量
                            if (detaildata.OutNum.ToString().IsNullOrEmpty()|| detaildata.OutNum==0)
                            {
                                dnum = data.Nums;
                            }
                            else
                            {
                                dnum = detaildata.OutNum + data.Nums;
                            }
                            if (dnum > detaildata.ScrapNums)
                            {
                                throw new BusException("物料数量大于报废单物料的剩余备货数量");
                            }
                           
                            //获取要出库的单个物料数量
                            double? warehouseNum = data.Nums;
                            string itsql = string.Empty;
                            string strLocalId = string.Empty;
                            string strStorId = string.Empty;
                            foreach (var item in IT_LocalDetaillist)
                            {
                                var trueorfalse = await _check.GetTrueOrFalse(item.MaterialId, item.StorId, item.LocalId);
                                if (trueorfalse.boolType == false)
                                {
                                    throw new BusException("仓库物料正在盘点中禁止下架出库");
                                }
                                if (warehouseNum > 0)
                                {
                                    strLocalId = item.LocalId;
                                    strStorId = item.StorId;
                                    //出库数量等于库存明细数量时
                                    if (item.Num == warehouseNum)
                                    {
                                        warehouseNum -= item.Num;
                                        if (item.OldOrNew == 0)
                                        {
                                            sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                                        }
                                        else if (item.OldOrNew == 1)
                                        {
                                            sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                                        }
                                        itsql += @" delete from IT_LocalDetail where Id='" + item.Id + "'; ";

                                    }
                                    else if (item.Num < warehouseNum)   //出库数量大于库存明细数量时
                                    {
                                        if (warehouseNum >= item.Num)
                                        {
                                            warehouseNum -= item.Num;
                                            if (item.OldOrNew == 0)
                                            {
                                                sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                                            }
                                            else if (item.OldOrNew == 1)
                                            {
                                                sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                                            }
                                            itsql += @" delete from IT_LocalDetail where Id='" + item.Id + "'; ";
                                        }
                                        else
                                        {
                                            if (item.OldOrNew == 0)
                                            {
                                                sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + warehouseNum + ",ScanNum=IFNULL(ScanNum,0)-" + warehouseNum + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                                            }
                                            else if (item.OldOrNew == 1)
                                            {
                                                sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + warehouseNum + ",ScanNum=IFNULL(ScanNum,0)-" + warehouseNum + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                                            }
                                            sqlMain += @" update IT_LocalDetail set Num=IFNULL(Num,0)-" + warehouseNum + " where Id='" + item.Id + "'; ";
                                            warehouseNum -= warehouseNum;
                                        }
                                    }
                                    else if (item.Num > warehouseNum) //出库数量小于库存明细数量时
                                    {
                                        item.Num -= warehouseNum;
                                        if (item.OldOrNew == 0)
                                        {
                                            sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + warehouseNum + ",ScanNum=IFNULL(ScanNum,0)-" + warehouseNum + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                                        }
                                        else if (item.OldOrNew == 1)
                                        {
                                            sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + warehouseNum + ",ScanNum=IFNULL(ScanNum,0)-" + warehouseNum + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                                        }
                                        sqlMain += @" update IT_LocalDetail set Num=IFNULL(Num,0)-" + warehouseNum + " where Id='" + item.Id + "'; ";
                                        warehouseNum -= warehouseNum;
                                    }

                                }
                                else
                                {
                                    continue;
                                }
                            }
                            sqlMain += @" update TD_ScrapDetail set OutNum=IFNULL(OutNum,0)+" + data.Nums + " where ParentId='" + ScrapId + "' and MaterialId='" + materialId + "' and LocationId='" + locationId + "'; ";
                            //获取要出库的单个物料数量
                            warehouseNum = data.Nums;

                            List<PB_Stock> PB_Stocklist = await Db.GetIQueryable<PB_Stock>().Where(x => x.MaterialId == materialId && x.LocationId == locationId && x.PackId == "").ToListAsync();
                            if (PB_Stocklist.Count > 0)
                            {
                                foreach (var item in PB_Stocklist)
                                {
                                    if (warehouseNum != 0)
                                    {
                                        //出库数量等于库存明细数量时
                                        if (item.StockNumber == warehouseNum)
                                        {
                                            warehouseNum -= item.StockNumber;
                                            sqlMain += @" delete from PB_Stock where Id='" + item.Id + "'; ";
                                        }
                                        else if (item.StockNumber < warehouseNum)   //出库数量大于库存明细数量时
                                        {
                                            if (warehouseNum >= item.StockNumber)
                                            {
                                                warehouseNum -= item.StockNumber;
                                                sqlMain += @" delete from PB_Stock where Id='" + item.Id + "'; ";
                                            }
                                            else
                                            {
                                                sqlMain += @" update PB_Stock set StockNumber=IFNULL(StockNumber,0)-" + warehouseNum + " where Id='" + item.Id + "'; ";
                                                warehouseNum -= warehouseNum;
                                            }
                                        }
                                        else if (item.StockNumber > warehouseNum) //出库数量小于库存明细数量时
                                        {
                                            item.StockNumber -= warehouseNum;
                                            sqlMain += @" update PB_Stock set StockNumber=IFNULL(StockNumber,0)-" + warehouseNum + " where Id='" + item.Id + "'; ";
                                            warehouseNum -= warehouseNum;
                                        }
                                    }
                                    else
                                    {
                                        continue;
                                    }
                                }
                            }
                            TD_ScrapDetail tD_ScrapDetail = await Db.GetIQueryable<TD_ScrapDetail>().Where(x => x.ParentId == ScrapId && x.MaterialId == materialId).FirstOrDefaultAsync();
                            //增加备货单明细日志
                            PB_UnLoadList pbdata = new PB_UnLoadList();
                            pbdata.Id = IdHelper.GetId();
                            pbdata.ParentId = tD_ScrapDetail.Id;
                            pbdata.LocalId = locationId;
                            pbdata.PackId = "";
                            pbdata.MaterialId = materialId;
                            pbdata.Nums = data.Nums;
                            pbdata.CreatorId = _operator.UserId;
                            pbdata.CreatorRealName = basedata.RealName;
                            pbdata.CreateTime = DateTime.Now;
                            pbdata.Deleted = false;
                            pbdata.JobId = "";
                            UnLoadList.Add(pbdata);
                            //增加出库日志
                            PB_StockLog pblog = new PB_StockLog();
                            pblog.Id = IdHelper.GetId();
                            pblog.PackId = "";
                            pblog.StorId = strStorId;
                            pblog.LocationId = locationId;
                            pblog.MaterialId = materialId;
                            pblog.StockNumber = data.Nums;
                            pblog.CreatorId = _operator.UserId;
                            pblog.CreatorName = basedata.RealName;
                            pblog.OperatorId = _operator.UserId;
                            pblog.Type = 1;
                            pblog.OrderID = "";
                            pblog.CreateTime = DateTime.Now;
                            pblog.State = 1;
                            StockLogList.Add(pblog);
                        }
                        else
                        {
                            throw new BusException("请检查货位上的库存物料是否满足需求");
                        }

                    }
                    else
                    {
                        if (tD_Scrap.State == 0)
                        {
                            throw new BusException("请审核后操作!");
                        }
                        else
                        {
                            throw new BusException("报废单已出库!");
                        }
                    }

                }
                else if (PackModel=="99") {
                    var MateraiId = data.MaterialQrCode.Split(',')[1].ToString();
                   
                    var tD_Scrap = await Db.GetIQueryable<TD_Scrap>().Where(m => m.Id == ScrapId).FirstOrDefaultAsync();
                    if (tD_Scrap.State == 1)
                    {
                        var td_scrap = await Db.GetIQueryable<TD_ScrapDetail>().Where(m => m.ParentId == tD_Scrap.Id && m.LocationId == locationId && m.MaterialId == MateraiId).FirstOrDefaultAsync();
                        if (td_scrap == null)
                        {
                            throw new BusException("请检查报废单是否存在该物料信息!");
                        }
                        PB_UnLoadList pB_UnLoadList = new PB_UnLoadList();
                        pB_UnLoadList.Id = IdHelper.GetId();
                        pB_UnLoadList.ParentId = tD_Scrap.Id;
                        pB_UnLoadList.LocalId = locationId;
                        pB_UnLoadList.PackId = "";
                        pB_UnLoadList.MaterialId = materialId;
                        pB_UnLoadList.Nums = data.Nums;
                        pB_UnLoadList.CreatorId = _operator.UserId;
                        pB_UnLoadList.CreatorRealName = _operator.UserName;
                        pB_UnLoadList.CreateTime = DateTime.Now;
                        pB_UnLoadList.Deleted = false;
                        pB_UnLoadList.JobId = "";

                        await Db.InsertAsync<PB_UnLoadList>(pB_UnLoadList);
                    }
                    else
                    {
                        if (tD_Scrap.State == 0)
                        {
                            throw new BusException("请审核后操作!");
                        }
                        else
                        {
                            throw new BusException("报废单已出库!");
                        }
                    }
                }
              
            }

            await Db.InsertAsync<PB_UnLoadList>(UnLoadList);

            await Db.InsertAsync<PB_StockLog>(StockLogList);
            await Db.ExecuteSqlAsync(sqlMain);
        }

        public async Task<ScrapOutDetail> GetScrapOutDetail(string QrCode, string LocationQrCode, string MaterialQrCode)
        {
            string ScrapId = QrCode.Split(',')[1].ToString();
            string LocationId = LocationQrCode.Split(',')[1].ToString();
            var pblocation =await Db.GetIQueryable<PB_Location>().Where(m=>m.Id== LocationId).FirstOrDefaultAsync();
            string PackModel = MaterialQrCode.Split(',')[0].ToString();
            string materialId = string.Empty;
            TD_Scrap db =await Db.GetIQueryable<TD_Scrap>().Where(m=>m.Id==ScrapId).FirstOrDefaultAsync();
            if (db == null)
            {
                throw new BusException("请扫描正确的报废单!");
            }
            else {
                if (PackModel=="04") {
                    var model = MaterialQrCode.Split(',');
                    if (model.Length > 2)
                    {
                        if (model.Length < 4)
                        {
                            throw new BusException("请扫描正确的二维码信息");
                        }
                        else
                        {
                            materialId = model?[3].ToString();
                        }
                    }
                    else
                    {
                        materialId = model?[1].ToString();
                    }
                    var TD_ScrapDetail =await Db.GetIQueryable<TD_ScrapDetail>().Where(m=>m.ParentId== ScrapId&&m.LocationId==LocationId&&m.MaterialId==materialId).FirstOrDefaultAsync();
                    if (TD_ScrapDetail==null) {
                        throw new BusException(" 请检查货位中的物料是否在报废单中!");
                    }
                    var pB_UpLoadList =await Db.GetIQueryable<PB_UnLoadList>().Where(m=>m.ParentId== TD_ScrapDetail .Id&& m.LocalId==LocationId&&m.MaterialId== materialId).ToListAsync();
                    var list= pB_UpLoadList.GroupBy(x => new { x.ParentId,x.LocalId,x.MaterialId }).Select(x => new { ParentId = x.Key.ParentId, LocalId = x.Key.LocalId, MaterialId = x.Key.MaterialId, Nums = x.Sum(i => i.Nums) }).FirstOrDefault();
                    var dbmater =await Db.GetIQueryable<PB_Material>().Where(m=>m.Id==materialId).FirstOrDefaultAsync();
                    if (dbmater==null) {
                        throw new BusException("物料信息有误!");
                    }
                    var PB_Stoarea =await Db.GetIQueryable<PB_StorArea>().Where(m=>m.Id== pblocation.AreaId).FirstOrDefaultAsync();
                    var PB_Rack = await Db.GetIQueryable<PB_Rack>().Where(m => m.Id == pblocation.RackId).FirstOrDefaultAsync();
                    ScrapOutDetail scrapOutDetail = new ScrapOutDetail();
                    scrapOutDetail.QrCode = QrCode;
                    scrapOutDetail.LocationQrCode = LocationQrCode;
                    scrapOutDetail.MaterialQrCode = MaterialQrCode;
                    scrapOutDetail.Name = dbmater.Name;
                    scrapOutDetail.Code = dbmater.Code;
                    scrapOutDetail.Spec = dbmater.Spec;
                    scrapOutDetail.ScrapNums = TD_ScrapDetail.ScrapNums;
                    scrapOutDetail.LocationName = PB_Stoarea.Name + "/" + PB_Rack.Name + "/" + pblocation.Name;
                    //获取已出库数量
                    scrapOutDetail.QuantityNums= (list == null ? 0 : list.Nums);
                    return scrapOutDetail;

                } else if (PackModel=="99") {
                    var model = MaterialQrCode.Split(',')[1].ToString();
             
                    var TD_ScrapDetail = await Db.GetIQueryable<TD_ScrapDetail>().Where(m => m.ParentId == ScrapId && m.LocationId == LocationId && m.MaterialId == model).FirstOrDefaultAsync();
                    if (TD_ScrapDetail == null)
                    {
                        throw new BusException(" 请检查货位中的物料是否在报废单中!");
                    }
                    var pB_UpLoadList = await Db.GetIQueryable<PB_UnLoadList>().Where(m => m.ParentId == TD_ScrapDetail.Id && m.LocalId == LocationId && m.MaterialId == model).ToListAsync();
                    var list = pB_UpLoadList.GroupBy(x => new { x.ParentId, x.LocalId, x.MaterialId }).Select(x => new { ParentId = x.Key.ParentId, LocalId = x.Key.LocalId, MaterialId = x.Key.MaterialId, Nums = x.Sum(i => i.Nums) }).FirstOrDefault();
                    var dbmater = await Db.GetIQueryable<PB_Material>().Where(m => m.Id == model).FirstOrDefaultAsync();
                    if (dbmater == null)
                    {
                        throw new BusException("物料信息有误!");
                    }
                    var PB_Stoarea = await Db.GetIQueryable<PB_StorArea>().Where(m => m.Id == pblocation.AreaId).FirstOrDefaultAsync();
                    var PB_Rack = await Db.GetIQueryable<PB_Rack>().Where(m => m.Id == pblocation.RackId).FirstOrDefaultAsync();
                    ScrapOutDetail scrapOutDetail = new ScrapOutDetail();
                    scrapOutDetail.QrCode = QrCode;
                    scrapOutDetail.LocationQrCode = LocationQrCode;
                    scrapOutDetail.MaterialQrCode = MaterialQrCode;
                    scrapOutDetail.Name = dbmater.Name;
                    scrapOutDetail.Code = dbmater.Code;
                    scrapOutDetail.Spec = dbmater.Spec;
                    scrapOutDetail.ScrapNums = TD_ScrapDetail.ScrapNums;
                    scrapOutDetail.LocationName = PB_Stoarea.Name + "/" + PB_Rack.Name + "/" + pblocation.Name;
                    //获取已出库数量
                    scrapOutDetail.QuantityNums = (list == null ? 0 : list.Nums);
                    return scrapOutDetail;
                }
            }
            return null;
        }
        /// <summary>
        /// 扫描报废单获取报废单信息
        /// </summary>
        /// <param name="QrCode">报废单二维码</param>
        /// <returns></returns>
        public async Task<TD_Scrap> GetAllScrap(string QrCode)
        {
            string ScrapId = QrCode.Split(',')[1].ToString();
            var TD_Scrap=await Db.GetIQueryable<TD_Scrap>().Where(m=>m.Id== ScrapId).FirstOrDefaultAsync();
            if (TD_Scrap != null)
            {
                if (TD_Scrap.State == 1)
                {
                    TD_Scrap tD_Scrap = new TD_Scrap();
                    tD_Scrap = TD_Scrap;
                    return tD_Scrap;
                }
                else {
                    if (TD_Scrap.State == 0) {
                        throw new BusException("请审核后操作!");
                    }
                    else {
                        throw new BusException("该报废单已出库!");
                    }
                }
            }
            else {
                throw new BusException("报废单号不正确!");
            }

           
        }

        /// <summary>
        /// PDA报废出库移除
        /// </summary>
        /// <param name="stockupQrCode">报废单二维码</param>
        /// <param name="packqrocde">包/物料/成品二维码</param>
        /// <param name="locationId">货位id</param>
        /// <param name="Nums">移除数量</param>
        /// <returns></returns>
        [Transactional]
        public async Task DeleteStockUpDetailListDataAsync(string stockupQrCode, string packqrocde, string locationId, double Nums)
        {
            List<PB_Stock> StockList = new List<PB_Stock>();
            List<PB_StockLog> StockLogList = new List<PB_StockLog>();
            List<IT_LocalDetail> LocalDetailList = new List<IT_LocalDetail>();
            Base_User basedata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            string stockupid = stockupQrCode.Split(',')?[1].ToString();   //备货单id
            string packid = string.Empty;
            string materialId = string.Empty;
            string jobid = string.Empty;
            string packmodel = packqrocde.Split(',')?[0].ToString();
            if (packmodel == "13")
            {
                packid = packqrocde.Split(',')?[1].ToString();
            }
            else if (packmodel == "04")
            {
                var model = packqrocde.Split(',');
                if (model.Length > 2)
                {
                    materialId = model?[3].ToString();
                }
                else
                {
                    materialId = model?[1].ToString();
                }
            }
            else if (packmodel == "14")
            {
                jobid = packqrocde.Split(',')?[1].ToString();
            }
            string sqlMain = string.Empty;
           
            //扫码包
            if (packmodel == "13")
            {
                PB_PackList pbdata = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == packid).FirstOrDefaultAsync();
                if (pbdata.PackageType == 0)
                {
                    Expression<Func<PB_UnLoadList, PB_Location, PB_Material, PB_UnLoadListDataListDTO>> packselect = (a, b, c) => new PB_UnLoadListDataListDTO
                    {
                        LocationId = b.Id,
                        StorId = b.StorId,
                        AreaId = b.AreaId,
                        RackId = b.RackId,
                        MeasureId = c.storageId
                    };
                    packselect = packselect.BuildExtendSelectExpre();
                    var packdata = from a in Db.GetIQueryable<PB_UnLoadList>().AsExpandable()
                                   join b in Db.GetIQueryable<PB_Location>() on a.LocalId equals b.Id into ab
                                   from b in ab.DefaultIfEmpty()
                                   join c in Db.GetIQueryable<PB_Material>() on a.MaterialId equals c.Id into ac
                                   from c in ac.DefaultIfEmpty()
                                   select @packselect.Invoke(a, b, c);
                    var unloaddata = await packdata.Where(x => x.PackId == packid).FirstOrDefaultAsync();
                    if (unloaddata == null)
                    {
                        throw new BusException("已移除不能重复移除");
                    }
                    //删除备货出库的明细
                    sqlMain += @" delete from PB_UnLoadList where PackId='" + packid + "'; ";
                    //修改包的状态为入库
                    sqlMain += @" update PB_PackList set Status=3 where Id='" + packid + "'; ";
                    //减去备货单明细的出库数量
                    sqlMain += @" update PB_PickUpList set ReadyNums=IFNULL(ReadyNums,0)-" + pbdata.Nums + " where ParentId='" + stockupid + "' and MaterialId='" + pbdata.MaterialId + "'; ";
                    //await ExecuteSqlAsync(sqlMain);
                    var pb_PickListSteps = Db.GetIQueryable<PB_PickListSteps>().Where(x => x.ParentId == stockupid && x.MaterialId == pbdata.MaterialId && x.ReadyNums > 0).ToList();

                    if (pb_PickListSteps.Count > 0)
                    {
                        bool Isfal = false;
                        double? nums = pbdata.Nums;
                        //string sqlupdate = "";
                        for (int i = pb_PickListSteps.Count - 1; i >= 0; i--)
                        {
                            var pb = await Db.GetIQueryable<PB_PickListSteps>().Where(m => m.Id == pb_PickListSteps[i].Id).FirstOrDefaultAsync();
                            nums = nums - pb.ReadyNums;
                            if (Isfal == false)
                            {
                                if (nums < 0)
                                {
                                    double? values = pb.ReadyNums - (nums + pb.ReadyNums);

                                    sqlMain += @"update  PB_PickListSteps set ReadyNums=" + values + " where Id='" + pb_PickListSteps[i].Id + "';";
                                    Isfal = true;
                                }
                                else
                                {
                                    sqlMain += @"update  PB_PickListSteps set ReadyNums=0 where Id='" + pb_PickListSteps[i].Id + "';";

                                }
                            }
                        }
                    }

                    PB_Stock stockdata = new PB_Stock();
                    stockdata.Id = IdHelper.GetId();
                    stockdata.PackId = packid;
                    stockdata.StorId = unloaddata.StorId;
                    stockdata.LocationId = unloaddata.LocationId;
                    stockdata.StockNumber = pbdata.Nums;
                    stockdata.MaterialId = pbdata.MaterialId;
                    stockdata.CreatorId = _operator.UserId;
                    stockdata.CreatorName = basedata.RealName;
                    stockdata.CreateTime = DateTime.Now;
                    stockdata.OperatorId = _operator.UserId;
                    stockdata.Type = 1;
                    stockdata.OrderID = stockupid;
                    stockdata.OldOrNew = pbdata.OldOrNew;
                    stockdata.AreaId = unloaddata.AreaId;
                    stockdata.RackId = unloaddata.RackId;
                    stockdata.JobId = "";
                    StockList.Add(stockdata);

                    PB_StockLog stockdatalog = new PB_StockLog();
                    stockdatalog.Id = IdHelper.GetId();
                    stockdatalog.PackId = packid;
                    stockdatalog.StorId = unloaddata.StorId;
                    stockdatalog.LocationId = unloaddata.LocationId;
                    stockdatalog.StockNumber = pbdata.Nums;
                    stockdatalog.MaterialId = pbdata.MaterialId;
                    stockdatalog.CreatorId = _operator.UserId;
                    stockdatalog.CreatorName = basedata.RealName;
                    stockdatalog.CreateTime = DateTime.Now;
                    stockdatalog.OperatorId = _operator.UserId;
                    stockdatalog.Type = 1;
                    stockdatalog.OrderID = stockupid;
                    stockdatalog.OldOrNew = pbdata.OldOrNew;
                    stockdatalog.State = 0;
                    stockdatalog.JobId = "";
                    StockLogList.Add(stockdatalog);

                    IT_LocalDetail itdata = new IT_LocalDetail();
                    itdata.Id = IdHelper.GetId();
                    itdata.StorId = unloaddata.StorId;
                    itdata.LocalId = unloaddata.LocationId;
                    itdata.MaterialId = pbdata.MaterialId;
                    itdata.MeasureId = unloaddata.MeasureId;
                    itdata.BarCode = pbdata.QrCode;
                    itdata.InTime = DateTime.Now;
                    itdata.CreateTime = DateTime.Now;
                    itdata.CreatorId = _operator.UserId;
                    itdata.Deleted = false;
                    itdata.Num = pbdata.Nums;
                    itdata.PackId = packid;
                    itdata.OldOrNew = pbdata.OldOrNew;
                    itdata.JobId = "";
                    LocalDetailList.Add(itdata);

                    if (pbdata.OldOrNew == 0)
                    {
                        sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)+" + pbdata.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + pbdata.Nums + " where MaterialId='" + pbdata.MaterialId + "' and StorId='" + unloaddata.StorId + "' and LocalId='" + unloaddata.LocationId + "'; ";
                    }
                    else if (pbdata.OldOrNew == 1)
                    {
                        sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + pbdata.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + pbdata.Nums + " where MaterialId='" + pbdata.MaterialId + "' and StorId='" + unloaddata.StorId + "' and LocalId='" + unloaddata.LocationId + "'; ";
                    }
                }
                else if (pbdata.PackageType == 1)
                {
                    Expression<Func<PB_UnLoadList, PB_Location, PB_Material, PB_UnLoadListDataListDTO>> packselect = (a, b, c) => new PB_UnLoadListDataListDTO
                    {
                        LocationId = b.Id,
                        StorId = b.StorId,
                        AreaId = b.AreaId,
                        RackId = b.RackId,
                        MeasureId = c.storageId
                    };
                    packselect = packselect.BuildExtendSelectExpre();
                    var packdata = from a in Db.GetIQueryable<PB_UnLoadList>().AsExpandable()
                                   join b in Db.GetIQueryable<PB_Location>() on a.LocalId equals b.Id into ab
                                   from b in ab.DefaultIfEmpty()
                                   join c in Db.GetIQueryable<PB_Material>() on a.MaterialId equals c.Id into ac
                                   from c in ac.DefaultIfEmpty()
                                   select @packselect.Invoke(a, b, c);
                    var unloaddata = await packdata.Where(x => x.PackId == packid).ToListAsync();

                    if (unloaddata == null)
                    {
                        throw new BusException("已移除不能重复移除");
                    }

                    //删除备货出库的明细
                    sqlMain += @" delete from PB_UnLoadList where PackId='" + packid + "'; ";
                    //修改包的状态为入库
                    sqlMain += @" update PB_PackList set Status=3 where Id='" + packid + "'; ";
                    //await ExecuteSqlAsync(sqlMain);

                    string strStorId = string.Empty;
                    string strLocalId = string.Empty;
                    string strAreaId = string.Empty;
                    string strRackId = string.Empty;

                    foreach (var item in unloaddata)
                    {
                        strStorId = item.StorId;
                        strLocalId = item.LocalId;
                        strAreaId = item.AreaId;
                        strRackId = item.RackId;
                        IT_LocalDetail itdata = new IT_LocalDetail();
                        itdata.Id = IdHelper.GetId();
                        itdata.StorId = item.StorId;
                        itdata.LocalId = item.LocalId;
                        itdata.MaterialId = item.MaterialId;
                        itdata.MeasureId = item.MeasureId;
                        itdata.BarCode = pbdata.QrCode;
                        itdata.InTime = DateTime.Now;
                        itdata.CreateTime = DateTime.Now;
                        itdata.CreatorId = _operator.UserId;
                        itdata.Deleted = false;
                        itdata.Num = item.Nums;
                        itdata.PackId = packid;
                        itdata.OldOrNew = pbdata.OldOrNew;
                        itdata.JobId = "";
                        LocalDetailList.Add(itdata);

                        //减去备货单明细的出库数量
                        sqlMain += @" update PB_PickUpList set ReadyNums=IFNULL(ReadyNums,0)-" + item.Nums + " where ParentId='" + stockupid + "' and MaterialId='" + item.MaterialId + "'; ";

                        if (pbdata.OldOrNew == 0)
                        {
                            sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)+" + item.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + item.Nums + " where MaterialId='" + item.MaterialId + "' and StorId='" + item.StorId + "' and LocalId='" + item.LocationId + "'; ";
                        }
                        else if (pbdata.OldOrNew == 1)
                        {
                            sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + item.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + item.Nums + " where MaterialId='" + item.MaterialId + "' and StorId='" + item.StorId + "' and LocalId='" + item.LocationId + "'; ";
                        }
                    }

                    //添加PB_Stock
                    PB_Stock stockdata = new PB_Stock();
                    stockdata.Id = IdHelper.GetId();
                    stockdata.PackId = packid;
                    stockdata.StorId = strStorId;
                    stockdata.LocationId = strLocalId;
                    stockdata.StockNumber = pbdata.Nums;
                    stockdata.MaterialId = pbdata.MaterialId;
                    stockdata.CreatorId = _operator.UserId;
                    stockdata.CreatorName = basedata.RealName;
                    stockdata.CreateTime = DateTime.Now;
                    stockdata.OperatorId = _operator.UserId;
                    stockdata.Type = 1;
                    stockdata.OrderID = stockupid;
                    stockdata.OldOrNew = pbdata.OldOrNew;
                    stockdata.AreaId = strAreaId;
                    stockdata.RackId = strRackId;
                    stockdata.JobId = "";
                    StockList.Add(stockdata);

                    //添加PB_StockLog
                    PB_StockLog stockdatalog = new PB_StockLog();
                    stockdatalog.Id = IdHelper.GetId();
                    stockdatalog.PackId = packid;
                    stockdatalog.StorId = strStorId;
                    stockdatalog.LocationId = strLocalId;
                    stockdatalog.StockNumber = pbdata.Nums;
                    stockdatalog.MaterialId = pbdata.MaterialId;
                    stockdatalog.CreatorId = _operator.UserId;
                    stockdatalog.CreatorName = basedata.RealName;
                    stockdatalog.CreateTime = DateTime.Now;
                    stockdatalog.OperatorId = _operator.UserId;
                    stockdatalog.Type = 1;
                    stockdatalog.OrderID = stockupid;
                    stockdatalog.OldOrNew = pbdata.OldOrNew;
                    stockdatalog.State = 0;
                    stockdatalog.JobId = "";
                    StockLogList.Add(stockdatalog);

                }
            }
            //扫码单个物料
            else if (packmodel == "04")
            {
                Expression<Func<PB_UnLoadList, PB_Location, TD_ScrapDetail, PB_Material, PB_UnLoadListDataListDTO>> packselect = (a, b, c, d) => new PB_UnLoadListDataListDTO
                {
                    LocationId = b.Id,
                    StorId = b.StorId,
                    AreaId = b.AreaId,
                    RackId = b.RackId,
                    PickListMainId = c.ParentId,
                    PickListId = c.Id,
                    MeasureId = d.storageId,
                };
                packselect = packselect.BuildExtendSelectExpre();
                var packdata = from a in Db.GetIQueryable<PB_UnLoadList>().AsExpandable()
                               join b in Db.GetIQueryable<PB_Location>() on a.LocalId equals b.Id into ab
                               from b in ab.DefaultIfEmpty()
                               join c in Db.GetIQueryable<TD_ScrapDetail>() on a.ParentId equals c.Id into ac
                               from c in ac.DefaultIfEmpty()
                               join d in Db.GetIQueryable<PB_Material>() on a.MaterialId equals d.Id into ad
                               from d in ad.DefaultIfEmpty()
                               select @packselect.Invoke(a, b, c, d);
                var unloaddata = await packdata.Where(x => x.PickListMainId == stockupid && x.MaterialId == materialId).FirstOrDefaultAsync();
                if (unloaddata == null)
                {
                    throw new BusException("已移除不能重复移除");
                }

                //删除备货出库的明细
                sqlMain += @" delete from PB_UnLoadList where MaterialId='" + unloaddata.MaterialId + "' and ParentId='" + unloaddata.PickListId + "' and LocalId='" + locationId + "' and Nums='" + Nums + "'  LIMIT 1; ";
                //减去备货单明细的出库数量
                sqlMain += @" update TD_ScrapDetail set OutNum=IFNULL(OutNum,0)-" + Nums + " where ParentId='" + stockupid + "' and MaterialId='" + unloaddata.MaterialId + "' AND LocationId='" + locationId + "'; ";
                PB_Stock stockdata = new PB_Stock();
                stockdata.Id = IdHelper.GetId();
                stockdata.PackId = "";
                stockdata.StorId = unloaddata.StorId;
                stockdata.LocationId = unloaddata.LocationId;
                stockdata.StockNumber = Nums;
                stockdata.MaterialId = unloaddata.MaterialId;
                stockdata.CreatorId = _operator.UserId;
                stockdata.CreatorName = basedata.RealName;
                stockdata.CreateTime = DateTime.Now;
                stockdata.OperatorId = _operator.UserId;
                stockdata.Type = 1;
                stockdata.OrderID = stockupid;
                stockdata.OldOrNew = 1;
                stockdata.AreaId = unloaddata.AreaId;
                stockdata.RackId = unloaddata.RackId;
                stockdata.JobId = "";
                StockList.Add(stockdata);
                //增加日志记录
                PB_StockLog stockdatalog = new PB_StockLog();
                stockdatalog.Id = IdHelper.GetId();
                stockdatalog.PackId = packid;
                stockdatalog.StorId = unloaddata.StorId;
                stockdatalog.StorId = unloaddata.StorId;
                stockdatalog.LocationId = unloaddata.LocationId;
                stockdatalog.StockNumber = Nums;
                stockdatalog.MaterialId = unloaddata.MaterialId;
                stockdatalog.CreatorId = _operator.UserId;
                stockdatalog.CreatorName = basedata.RealName;
                stockdatalog.CreateTime = DateTime.Now;
                stockdatalog.OperatorId = _operator.UserId;
                stockdatalog.Type = 1;
                stockdatalog.OrderID = stockupid;
                stockdatalog.OldOrNew = 1;
                stockdatalog.State = 0;
                stockdatalog.JobId = "";
                StockLogList.Add(stockdatalog);

                IT_LocalDetail itdata = new IT_LocalDetail();
                itdata.Id = IdHelper.GetId();
                itdata.StorId = unloaddata.StorId;
                itdata.LocalId = unloaddata.LocationId;
                itdata.MaterialId = unloaddata.MaterialId;
                itdata.MeasureId = unloaddata.MeasureId;
                itdata.BarCode = packqrocde;
                itdata.InTime = DateTime.Now;
                itdata.CreateTime = DateTime.Now;
                itdata.CreatorId = _operator.UserId;
                itdata.Deleted = false;
                itdata.Num = Nums;
                itdata.PackId = packid;
                itdata.OldOrNew = 1;
                itdata.JobId = "";
                LocalDetailList.Add(itdata);

                sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + Nums + ",ScanNum=IFNULL(ScanNum,0)+" + Nums + " where MaterialId='" + unloaddata.MaterialId + "' and StorId='" + unloaddata.StorId + "' and LocalId='" + unloaddata.LocationId + "'; ";

            }
            //扫码成品
            else if (packmodel == "14")
            {
              
                Expression<Func<PB_UnLoadList, PB_Material, PB_Location, UnLoadListMaterialDTO>> select = (a, b, c) => new UnLoadListMaterialDTO
                {
                    MaterialName = b.Name,
                    Price = b.Price,
                    storageId = b.storageId,
                    StorId = c.StorId,
                };
                select = select.BuildExtendSelectExpre();
                var q = from a in Db.GetIQueryable<PB_UnLoadList>().AsExpandable()
                        join b in Db.GetIQueryable<PB_Material>() on a.ParentId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        join c in Db.GetIQueryable<PB_Location>() on a.LocalId equals c.Id into ac
                        from c in ac.DefaultIfEmpty()
                        select @select.Invoke(a, b, c);
                var unjobdata = await q.Where(x => x.JobId == jobid).FirstOrDefaultAsync();
                if (unjobdata == null)
                {
                    throw new BusException("成品已移除不能重复移除");
                }

                PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid).FirstOrDefaultAsync();

                //恢复库存汇总数量
                if (jobdata.OldOrNew == 0)
                {
                    sqlMain += @"update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)+1,ScanNum=IFNULL(ScanNum,0)+1 where LocalId='" + unjobdata.LocalId + "' and MaterialId='" + unjobdata.MaterialId + "'; ";
                }
                else if (jobdata.OldOrNew == 1)
                {
                    sqlMain += @"update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+1,ScanNum=IFNULL(ScanNum,0)+1 where LocalId='" + unjobdata.LocalId + "' and MaterialId='" + unjobdata.MaterialId + "'; ";
                }
                //恢复物料的审核前数量
                sqlMain += @" update PB_Material set ScanNum=IFNULL(ScanNum,0)+1 where Id='" + unjobdata.MaterialId + "'; ";
                //修改备货单明细已备货数量
                sqlMain += @" update TD_ScrapDetail set OutNum=IFNULL(OutNum,0)-1 where Id='" + unjobdata.ParentId + "'; ";
                //删除下架扫码记录
                sqlMain += @" delete from PB_UnLoadList where JobId='" + jobid + "'; ";
                var pb_PickListSteps = Db.GetIQueryable<PB_PickListSteps>().Where(x => x.ParentId == stockupid && x.MaterialId == unjobdata.MaterialId && x.ReadyNums != null && x.ReadyNums > 0 && x.LocationId == unjobdata.LocalId).ToList();

                

                //库存明细表
                IT_LocalDetail detdata = new IT_LocalDetail();
                detdata.Id = IdHelper.GetId();
                detdata.StorId = unjobdata.StorId;
                detdata.LocalId = unjobdata.LocalId;
                detdata.MaterialId = unjobdata.MaterialId;
                detdata.MeasureId = unjobdata.storageId;
                detdata.InTime = DateTime.Now;
                detdata.CreateTime = DateTime.Now;
                detdata.CreatorId = _operator.UserId;
                detdata.Deleted = false;
                detdata.Num = 1;
                detdata.BarCode = h_FinishedProduct + "," + jobid;
                detdata.PackId = "";
                detdata.Price = unjobdata.Price;
                detdata.Amount = unjobdata.Price;
                detdata.OldOrNew = jobdata.OldOrNew;
                detdata.RecId = "";
                detdata.JobId = jobid;
                LocalDetailList.Add(detdata);

                //插入货架上存放货物存明细表
                PB_Stock stockdata = new PB_Stock();
                stockdata.Id = IdHelper.GetId();
                stockdata.PackId = "";
                stockdata.StorId = unjobdata.StorId;
                stockdata.LocationId = unjobdata.LocalId;
                stockdata.StockNumber = 1;
                stockdata.MaterialId = unjobdata.MaterialId;
                stockdata.CreatorId = _operator.UserId;
                stockdata.CreatorName = basedata.RealName;
                stockdata.CreateTime = DateTime.Now;
                stockdata.OperatorId = _operator.UserId;
                stockdata.OrderID = stockupid;
                stockdata.Type = 1;
                stockdata.OldOrNew = jobdata.OldOrNew;
                stockdata.CirBillId = "";
                stockdata.JobId = jobid;
                StockList.Add(stockdata);

                //增加入库日志
                PB_StockLog stocklog = new PB_StockLog();
                stocklog.Id = IdHelper.GetId();
                stocklog.PackId = "";
                stocklog.MaterialId = unjobdata.MaterialId;
                stocklog.StorId = unjobdata.StorId;
                stocklog.LocationId = unjobdata.LocalId;
                stocklog.StockNumber = 1;
                stocklog.CreatorId = _operator.UserId;
                stocklog.CreatorName = basedata.RealName;
                stocklog.CreateTime = DateTime.Now;
                stocklog.Type = 1;
                stocklog.OrderID = stockupid;
                stocklog.State = 0;
                stocklog.OldOrNew = jobdata.OldOrNew;
                stocklog.CirBillId = "";
                stocklog.JobId = jobid;
                StockLogList.Add(stocklog);

            }

            await Db.InsertAsync<PB_Stock>(StockList);

            await Db.InsertAsync<PB_StockLog>(StockLogList);

            await Db.InsertAsync<IT_LocalDetail>(LocalDetailList);

            await ExecuteSqlAsync(sqlMain);

        }

        /// <summary>
        /// 获取报废单数据
        /// </summary>
        /// <param name="stockupQrCode"></param>
        /// <returns></returns>
        public async Task<List<PB_UnLoadListDataDTO>> GetStockUpDetailListDataAsync(string stockupQrCode)
        {
            string stockupid = stockupQrCode.Split(',')?[1].ToString();

            string sql = @"select * from (
 select b.PackId,b.MaterialId,b.JobId,c.BoxNo,c.BoxName,(concat(e.`Name`,'/',f.`Name`,'/',d.`Name`)) as LocalName,g.Spec as MaterialSpec,b.Nums as StockNumber,b.CreateTime,c.QrCode,b.LocalId	 from TD_ScrapDetail as a join PB_UnLoadList as b on a.Id=b.ParentId join PB_PackList as c on b.PackId=c.Id join PB_Location as d on b.LocalId=d.Id join PB_StorArea as e on d.AreaId=e.Id join PB_Rack as f on d.RackId=f.Id left join PB_Material as g on b.MaterialId=g.Id where a.ParentId='{0}' and  c.PackageType=0     
  UNION ALL 	 
  select PackId,'' as MaterialId,'' as JobId,BoxNo,BoxName,LocalName,'' as MaterialSpec,SUM(StockNumber) as StockNumber,CreateTime,QrCode,LocalId from (	
 select b.PackId,b.MaterialId,c.BoxNo,c.BoxName,(concat(e.`Name`,'/',f.`Name`,'/',d.`Name`)) as LocalName,g.Spec as MaterialSpec,b.Nums as StockNumber,DATE_FORMAT(b.CreateTime,'%Y-%m-%d') as CreateTime,c.QrCode,b.LocalId from TD_ScrapDetail as a join PB_UnLoadList as b on a.Id=b.ParentId join PB_PackList as c on b.PackId=c.Id join PB_Location as d on b.LocalId=d.Id join PB_StorArea as e on d.AreaId=e.Id join PB_Rack as f on d.RackId=f.Id left join PB_Material as g on b.MaterialId=g.Id where a.ParentId='{0}' and  c.PackageType=1 
 )as t group by PackId,BoxNo,BoxName,LocalName,CreateTime,QrCode ,LocalId    
  UNION all 	
  select b.PackId,b.MaterialId,b.JobId,c.Id as BoxNo,c.Name as BoxName,(concat(e.`Name`,'/',f.`Name`,'/',d.`Name`)) as LocalName,c.Spec as MaterialSpec,b.Nums as StockNumber,b.CreateTime,concat('04,',b.MaterialId) as QrCode,b.LocalId from TD_ScrapDetail as a join PB_UnLoadList as b on a.Id=b.ParentId join PB_Material as c on b.MaterialId=c.Id join PB_Location as d on b.LocalId=d.Id join PB_StorArea as e on d.AreaId=e.Id join PB_Rack as f on d.RackId=f.Id where a.ParentId='{0}' and b.PackId='' and b.JobId=''
  UNION all 	
  select b.PackId,b.MaterialId,b.JobId,c.Id as BoxNo,c.Name as BoxName,(concat(e.`Name`,'/',f.`Name`,'/',d.`Name`)) as LocalName,c.Spec as MaterialSpec,b.Nums as StockNumber,b.CreateTime,concat('14,',b.JobId) as QrCode,b.LocalId from TD_ScrapDetail as a join PB_UnLoadList as b on a.Id=b.ParentId join PB_Material as c on b.MaterialId=c.Id join PB_Location as d on b.LocalId=d.Id join PB_StorArea as e on d.AreaId=e.Id join PB_Rack as f on d.RackId=f.Id where a.ParentId='{0}' and b.PackId='' and b.JobId!=''
) as t order by CreateTime desc ";
            string sqlMain = string.Format(sql, stockupid);
            return await Db.GetListBySqlAsync<PB_UnLoadListDataDTO>(sqlMain);
        }
       /// <summary>
       /// PDA报废出库操作
       /// </summary>
       /// <param name="ScrapId">报废单id</param>
       /// <returns></returns>
        [Transactional]
        public async Task SubmitScrapDataAsync(string ScrapId)
        {
           //获取用户信息
            Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            Expression<Func<TD_ScrapDetail, PB_Material, TD_ScrapDetailPriceDTO>> packselect = (a, b) => new TD_ScrapDetailPriceDTO
            {
                Price = b.Price
            };
            packselect = packselect.BuildExtendSelectExpre();
            var packdata = from a in Db.GetIQueryable<TD_ScrapDetail>().AsExpandable()
                           join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                           from b in ab.DefaultIfEmpty()
                           select @packselect.Invoke(a, b);
            var stockupData = packdata.Where(x => x.ParentId == ScrapId).ToList();
            List<string> listdata = new List<string>();
            string sqlMain = "";

            double dbnum = 0;
            double dbTotalAmt = 0;
            //出库单Id
            string outid = IdHelper.GetId();
            List<TD_OutStorDetail> listdetaildata = new List<TD_OutStorDetail>();
            int i = 0;
            string StorId = string.Empty;
            string AreaId = string.Empty;
            string RackId = string.Empty;
            foreach (var item in stockupData)
            {
                if (i == 0)
                {
                    var locadata = await Db.GetIQueryable<PB_Location>().Where(x => x.Id == item.LocationId).FirstOrDefaultAsync();
                    StorId = locadata.StorId;
                    AreaId = locadata.AreaId;
                    RackId = locadata.RackId;
                }
                TD_OutStorDetail outdetaildata = new TD_OutStorDetail();
                outdetaildata.Id = IdHelper.GetId();
                outdetaildata.StorId = StorId;
                outdetaildata.OutStorId = outid;
                outdetaildata.LocalId = item.LocationId;
                outdetaildata.AreaId = AreaId;
                outdetaildata.RackId = RackId;
                outdetaildata.MaterialId = item.MaterialId;
                outdetaildata.OutNum = Convert.ToDouble(item.OutNum);
                outdetaildata.Price = Convert.ToDouble(item.Price);
                outdetaildata.TotalAmt = Convert.ToDouble(item.OutNum) * Convert.ToDouble(item.Price);
                dbnum += Convert.ToDouble(item.OutNum);
                dbTotalAmt += outdetaildata.TotalAmt;
                outdetaildata.CreatorId = _operator.UserId;
                outdetaildata.CreateTime = DateTime.Now;
                outdetaildata.Deleted = false;
                listdetaildata.Add(outdetaildata);
                i++;
            }
            
            //添加出库明细表
            List<TD_OutStorRecord> listtrecorddata = new List<TD_OutStorRecord>();
            var listd = listdetaildata.GroupBy(x => new { x.StorId, x.LocalId, x.OutStorId, x.MaterialId, x.Price }).Select(x => new { StorId = x.Key.StorId, LocalId = x.Key.LocalId, OutStorId = x.Key.OutStorId, MaterialId = x.Key.MaterialId, Price = x.Key.Price, Nums = x.Sum(n => n.OutNum) });
            foreach (var item in listd)
            {
                TD_OutStorRecord recodata = new TD_OutStorRecord();
                recodata.Id = IdHelper.GetId();
                recodata.StorId = item.StorId;
                recodata.OutStorId = item.OutStorId;
                recodata.MaterialId = item.MaterialId;
                recodata.OutNum = item.Nums;
                recodata.Price = item.Price;
                recodata.TotalAmt = item.Nums * item.Price;
                recodata.CreateTime = DateTime.Now;
                recodata.CreatorId = _operator.UserId;
                recodata.Deleted = false;
                listtrecorddata.Add(recodata);
            }
            //创建报废出库单
            TD_OutStorage outdata = new TD_OutStorage();
            outdata.Id = outid;
            outdata.Code = GetTimeStamp();
            outdata.OutTime = DateTime.Now;
            outdata.StorageId = StorId;
            outdata.OutType = "OtherOut";
            outdata.RefCode = ScrapId;
            outdata.ProjectId ="";
            outdata.DesignId ="";
            outdata.OutNum = dbnum;
            outdata.Status = 0;
            outdata.TotalAmt = dbTotalAmt;
            outdata.CreatorId = _operator.UserId;
            outdata.CreateTime = DateTime.Now;
            outdata.Deleted = false;
            outdata.QrCode = h_OutStorage + "," + outid;
            outdata.DepId = userdata.FactoryId;
            outdata.Remarks = "待维报废";
            outdata.FactoryId = userdata.FactoryId;
            //查询库存占用量是否满足
            Expression<Func<TD_ScrapDetail, IT_LocalMaterial, PickListLocaMaterialDTO>> pickselect = (a, b) => new PickListLocaMaterialDTO
            {
                PickMainId = a.ParentId,
                MaterialId = a.MaterialId,
                LocalId = a.LocationId,
                StockVolume = a.ScrapNums,
                Nums_R = b.Nums_R == null ? 0 : b.Nums_R,
                SurplusNums = (b.Nums_R == null ? 0 : b.Nums_R) - a.ScrapNums
            };
            pickselect = pickselect.BuildExtendSelectExpre();
            var pickq = from a in Db.GetIQueryable<TD_ScrapDetail>().AsExpandable()
                        join b in Db.GetIQueryable<IT_LocalMaterial>() on new { MaterialId = a.MaterialId, LocalId = a.LocationId } equals new { MaterialId = b.MaterialId, LocalId = b.LocalId } into ab
                        from b in ab.DefaultIfEmpty()
                        select @pickselect.Invoke(a, b);
            var picklist = await pickq.Where(x => x.PickMainId == ScrapId).ToListAsync();
            var GreaterThanZero = picklist.Where(x => x.SurplusNums < 0).ToList();
          
            //更新库存占用量
            var listdetdata = await Db.GetIQueryable<TD_ScrapDetail>().Where(x => x.ParentId == ScrapId).ToListAsync();
            foreach (var item in listdetdata)
            {
                sqlMain += @" update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)-" + item.ScrapNums + " where MaterialId='" + item.MaterialId + "' and LocalId='" + item.LocationId + "'; ";
            }
            //修改报废单状为已出库
            sqlMain += @" update TD_Scrap set State=2  where id='" + ScrapId + "'; ";
            await Db.InsertAsync<TD_OutStorDetail>(listdetaildata);
            await Db.InsertAsync<TD_OutStorRecord>(listtrecorddata);
            await Db.InsertAsync<TD_OutStorage>(outdata);
            await ExecuteSqlAsync(sqlMain);
        }

        public async Task ToScrapexamine(string Id)
        {
            string sql = "Update  TD_Scrap set State=1 where Id='" + Id+"'";
            await Db.ExecuteSqlAsync(sql);
        }
       public async Task< List<TD_ScrapDetailDto>>GetScrapDetailDto(string Parentid, string LocationId, string MaterName) {
            string sql = "SELECT IFNULL(a.ScrapNums, 0)  ScrapNums,IFNULL(a.OutNum, 0) OutNum,b.`Name` MaterialIdName,a.MaterialId MaterialId, b.Spec MaterSpec,b.Code materialCode FROM TD_ScrapDetail  AS a LEFT JOIN PB_Material as b on a.MaterialId = b.Id WHERE a.ParentId = '" + Parentid+"' AND a.LocationId = '"+LocationId+"'";
            if (!MaterName.IsNullOrEmpty()) {
                sql += "  AND (b.`Name` LIKE '%" + MaterName + "%' OR b.`Code` LIKE '%" + MaterName + "%' )";
            }
            var list =await Db.GetListBySqlAsync<TD_ScrapDetailDto>(sql);
            return list;
        }
        #endregion

        #region 私有成员

        #endregion
    }
}